package com.yonyou.brigade.third_parties.smectrip.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.third_parties.smectrip.constants.SmeCtripConstants;
import com.yonyou.brigade.util.operateutil.RedisUtils;
import com.yonyou.brigade.util.resultutil.HttpSendUtils;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * Created by Administrator on 2018/12/25.
 */
@Service
public class SmeCtripUtil {
    @Value("${smectrip.url}")
    private  String URL;

    @Autowired
    private RedisUtils redisUtils;

    private Logger logger= LoggerFactory.getLogger(this.getClass());

    /**
     * 获取业务调用需要的ticket
     *
     * @return
     */
    public String getBusinessTicket(String tenantid, String appkey, String appSecurity){
        //先从Redis中取，如果没有调接口
        String ticket = "";
        try {
            if (redisUtils.hasKey("SME_BUSINESS_TICKET_" + tenantid)){
                ticket = redisUtils.getValue("SME_BUSINESS_TICKET_" + tenantid);
                logger.info("从redis中获取携程商旅通ticket ：" + ticket );
            }else {
                JSONObject paramJson = new JSONObject();
                paramJson.put("AppKey",appkey);
                paramJson.put("AppSecurity",appSecurity);

                logger.info("携程商旅通，获取登录部门人员同步等ticket，请求数据->" + paramJson.toJSONString());
                String respStr = HttpSendUtils.sendPost(URL + SmeCtripConstants.BUSINESS_TICKET_URL,paramJson.toString());
                logger.info("携程商旅通，获取登录部门人员同步等ticket，返回数据->" + respStr);

                JSONObject respJson = null;
                try{
                    respJson = JSON.parseObject(respStr);
                }catch (Exception e){
                    logger.error(e.getMessage());
                    throw new BusinessException(e.toString());
                }

                if(!respJson.getBoolean("Success")){
                    logger.error("携程商旅通调用异常: " + respJson.getString("Message"));
                    throw new RuntimeException("携程商旅通调用异常" + respJson.getString("Message"));
                }

                //获取 Ticket
                ticket = respJson.getString("Token");
                //Redis中放两个小时
                redisUtils.setKey("SME_BUSINESS_TICKET_" + tenantid,ticket,120);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ticket;
    }


    public String getLoginTicket(String appKey, String appSecurity, int tokenType){
        JSONObject paramJson = new JSONObject();
        paramJson.put("appKey",appKey);
        paramJson.put("appSecurity",appSecurity);
        paramJson.put("TokenType",tokenType);

        //Json 串
        String ticketPostString = paramJson.toJSONString();
        //POST
        String ticketResponse = HttpSendUtils.sendPost(URL + SmeCtripConstants.LOGIN_TICKET_URL,ticketPostString);

        JSONObject respJson = null;
        try{
            respJson = JSON.parseObject(ticketResponse);
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        if(!respJson.getBoolean("Success")){
            logger.error("携程商旅通调用异常: " + respJson.getString("Message"));
            throw new RuntimeException("携程商旅通调用异常: " + respJson.getString("Message"));
        }
        //获取 Ticket
        String token = respJson.getString("Token");
        return token;
    }


    /**
     * 获取订单取数需要的ticket
     */
    public String getSearchOrderTicket(String tenantid,String appkey, String appSecurity){
        //先从Redis中取，如果没有调接口
        String ticket = "";
        try {
            if (redisUtils.hasKey("SME_SEARCHORDER_TICKET_" + tenantid)){
                ticket = redisUtils.getValue("SME_SEARCHORDER_TICKET_" + tenantid);
                logger.info("从redis中获取携程商旅通ticket ：" + ticket );
            }else {
                JSONObject paramJson = new JSONObject();
                paramJson.put("AppKey",appkey);
                paramJson.put("AppSecurity",appSecurity);

                logger.info("携程商旅通，订单取数ticket，请求参数->" + paramJson.toJSONString());
                String respStr = HttpSendUtils.sendPost(URL + SmeCtripConstants.SEARCHORDER_TICKET_URL,paramJson.toJSONString());
                logger.info("携程商旅通，订单取数ticket,返回参数->" + respStr);

                JSONObject respJson = null;
                try{
                    respJson = JSON.parseObject(respStr);
                }catch (Exception e){
                    logger.error(e.getMessage(),e);
                    throw new BusinessException("获取携程商旅通ticket异常");
                }

                JSONObject statusJson = respJson.getJSONObject("Status");
                boolean success = statusJson.getBoolean("Success");
                if (!success){
                    String message = statusJson.getString("Message");
                    logger.error("获取ticket失败->" + message);
                    throw new BusinessException("获取ticket失败->" + message);
                }
                //获取 Ticket
                ticket = respJson.getString("Ticket");
                //Redis中放两个小时
                redisUtils.setKey("SME_SEARCHORDER_TICKET_" + tenantid,ticket,120);
                }
            }catch (Exception e){
            e.printStackTrace();
        }
        return ticket;
    }
}